from typing import Optional, List
from pydantic import BaseModel, EmailStr, Field

from app.schemas.base import BaseSchema, TimestampMixin, TenantMixin


class DeptCreate(BaseModel):
    """创建部门"""
    name: str = Field(..., min_length=1, max_length=30, description="部门名称")
    parent_id: int = Field(0, description="父部门ID")
    order_num: int = Field(0, description="显示顺序")
    leader: Optional[str] = Field(None, max_length=20, description="负责人")
    phone: Optional[str] = Field(None, pattern=r"^1[3-9]\d{9}$", description="联系电话")
    email: Optional[EmailStr] = Field(None, description="邮箱")
    status: bool = Field(True, description="部门状态")


class DeptUpdate(BaseModel):
    """更新部门"""
    name: Optional[str] = Field(None, min_length=1, max_length=30, description="部门名称")
    parent_id: Optional[int] = Field(None, description="父部门ID")
    order_num: Optional[int] = Field(None, description="显示顺序")
    leader: Optional[str] = Field(None, max_length=20, description="负责人")
    phone: Optional[str] = Field(None, pattern=r"^1[3-9]\d{9}$", description="联系电话")
    email: Optional[EmailStr] = Field(None, description="邮箱")
    status: Optional[bool] = Field(None, description="部门状态")


class DeptResponse(BaseSchema, TimestampMixin, TenantMixin):
    """部门响应"""
    id: int
    name: str
    parent_id: int
    ancestors: str
    order_num: int
    leader: Optional[str] = None
    phone: Optional[str] = None
    email: Optional[str] = None
    status: bool
    user_count: int = 0
    children: List["DeptResponse"] = []


class DeptTreeResponse(BaseModel):
    """部门树响应"""
    departments: List[DeptResponse]


class DeptUserResponse(BaseModel):
    """部门用户响应"""
    dept_id: int
    dept_name: str
    users: List[dict]


# 解决前向引用问题
DeptResponse.model_rebuild()